import Vue from 'vue';
import { ref } from '@vue/composition-api'
import staticConst from "@/js/const/StaticConst.js";
import https from "@/js/https/Https.js";
import config from "@/js/conf/Config.js";
import downloadFile from "@/js/upload/DownloadFile.js";
import ExcelExporter from '@/utils/excelExport.js'
import { formatTimeString } from '@/utils/common.js'

const PAGE_SIZE = 1
// 创建一个单例状态
const state = {

    reqQuery: ref({
        storeid: "", //非必须 仓库筛选 默认所有
        group: "", //非必须 报表类型 1 日报 2月报 3季报  5 自定义时间的日报 默认按日统计
        stime: "", //非必须 自定义时间统计 开始时间 格式"2020-01-28"
        dtime: "", //分页参数  默认为1 该参数仅为日报时候使用， 其他条件不参与分页
        page: 1, //分页参数  默认为1 该参数仅为日报时候使用， 其他条件不参与分页
        is_yy: 1, //预约板块1是2 否 默认否
        uid_cp: "", //成员id
        pfrom: 0, //非必须 分页参数 - 页面
        pnum: staticConst.PAGE_SIZE, //非必须 分页参数 - 页面显示数量
    }),

    // 一级页面数据
    is_soll: ref(true),
    saleFlowsList: ref([]),
    count_ls: ref([]),
    loading: ref(false),
    hasMore: ref(true),
    store_ls: ref([]),
    staff_ls: ref([]),
    group_ls: ref([]),
    top_ls: ref([]),
    count_all: ref({}),

    // 二级页面数据
    is_2soll: ref(true),
    sale2FlowsList: ref([]),
    count_2ls: ref([]),
    loading2: ref(false),
    hasMore2: ref(true),
    count_2all: ref({}),
    sale_title: ref('采购流水'),
    sale_2title: ref('采购流水'),
    sale_day_title: ref('采购流水'),

    // 专门获取日报表列表
    count_day_ls: ref([]),
    count_day_all: ref({}),

    // 日数据弹窗
    shopSellPfrom: 0,// 日翻页数据
    shopsell_count_all: ref({}),
    shopsell_count__ls: ref([]),
    hasMoreShopSell: ref(true),
    fromTypes: ref(''),

    dateArray: ref([]),
    sale_day_timestr: ref(''),
    stime_type: ref(1), // 非必须 时间筛选  1日 2月 3季 4年 5 自定义  默认为1 此项可不填
    sale_day_old_timestr: ref(''), // 非必须 时间筛选 开始时间 格式"2020-01-28"
    is_quarter: ref(''), // 是否是点击季度进入月份

    // 仓库类目数量
    count_warehouse_ls: ref([]),
    count_warehouse_all: ref({}),
    warehouse_currentId: ref(''),
    warehouse_loading: ref(false),
    warehouse_hasMore: ref(true),
    warehouse_class_info: ref({}),
    warehouse_class_list: ref([]),
    warehouse_class_list_loading: ref(false),
    warehouse_pfrom: ref(0),
    warehouse_clickItem: ref({}),
    warehouse_showBack: ref(false),


    // 第二个表格商品
    warehouse_goods_list: ref([]),
    warehouse_goods_list_loading: ref(false),
    warehouse_goods_list_hasMore: ref(true),
    warehouse_goods_list_pfrom: ref(0),
    warehouse_goods_list_pnum: ref(staticConst.PAGE_SIZE),
    warehouse_catTitle: ref(''),

    // 点击第二个表格商品
    warehouse_goods_info: ref({}),
    warehouse_goods_list_ls: ref([]),
    warehouse_goods_info_loading: ref(false),
    warehouse_gdid: ref(''),

    // 仓库流水
    warehouse_flow_info: ref({}),
    warehouse_flow_list: ref([]),
    warehouse_flow_shop_info: ref({}),
    warehouse_flow_list_loading: ref(false),
    warehouse_flow_list_hasMore: ref(true),
    warehouse_flow_list_pfrom: ref(0),

    // 仓库流水详情
    warehouse_flow_detail: ref({}),
    warehouse_flow_row_info: ref({}),
}

export const usePurchaseState = () => {

    const resetState = () => {
        state.count_ls.value = []
        state.count_all.value = {}
        state.store_ls.value = []
        state.staff_ls.value = []
        state.top_ls.value = []
        state.reqQuery.value.page = 1
        state.hasMore.value = true
        state.loading.value = false
    }

    const reset2State = () => {
        state.is_2soll.value = true
        state.sale2FlowsList.value = []
        state.count_2ls.value = []
        state.loading2.value = false
        state.hasMore2.value = true
        state.count_2all.value = {}
    }

    const loadReportShopConut = () => {
        let param = state.reqQuery.value;
        state.loading.value = true
        // 如果是第一页，先重置数据
        if (param.page === 1) {
            resetState()
        }
        https.getReportPuchaseConut(param, back);
        function back(data) {
            state.loading.value = false
            if (!data) {
                return;
            }
            if (data.status == 1) {
                if (!data.data) {
                    return;
                }
                data = data.data;
                // 总金额
                state.count_all.value = data?.count_all || {}

                // 列表 - 根据timestr去重
                const newData = data?.count_ls || []
                const existingTimestrs = new Set(state.count_ls.value.map(item => item.timestr))
                const uniqueNewData = newData.filter(item => !existingTimestrs.has(item.timestr))
                state.count_ls.value = state.count_ls.value.concat(uniqueNewData)

                state.hasMore.value = (data?.count_ls && data?.count_ls?.length) >= PAGE_SIZE

                // 仓库
                state.store_ls.value = (data?.store_ls || []).map(item => ({
                    value: item.id,
                    label: item.name
                }))
                state.store_ls.value.unshift({
                    value: '',
                    label: '全部仓库'
                })

                // 经手人
                state.staff_ls.value = (data?.staff_ls || []).map(item => ({
                    value: item.id,
                    label: item.name
                }))
                state.staff_ls.value.unshift({
                    value: '',
                    label: '全部成员'
                })

                // 日期
                state.group_ls.value = (data?.group || [])
                state.group_ls.value.unshift({
                    id: '',
                    name: '全部日期'
                })

                // 排行榜
                if (state.reqQuery.value.page == 1) {
                    state.top_ls.value = (data?.top || [])
                    console.log("state.top_ls.value-x-", state.top_ls.value)
                }
            }
        }
    }

    const loadMoreData = () => {
        // 如果还有更多数据，则加载更多数据
        if (state.loading.value || !state.hasMore.value) {
            return
        }
        state.reqQuery.value.page += 1
        loadReportShopConut()
    }

    // 选择筛选
    const selectHandleChange = (value) => {
        if (state.loading.value) return;
        state.reqQuery.value.page = 1
        state.count_ls.value = []
        loadReportShopConut()
    }

    // 选择日期
    const selectDate = (value) => {
        if (value == state.reqQuery.value.group) {
            return
        }
        state.reqQuery.value.group = value
        if (state.reqQuery.value.group != 5) {
            state.reqQuery.value.stime = ''
            state.reqQuery.value.dtime = ''
            state.dateArray.value = []
        }
        state.reqQuery.value.page = 1
        state.count_ls.value = []
        state.hasMore.value = true
        setTimeout(() => {
            loadReportShopConut()
        }, 100)
    }

    // 导出
    const exportData = async (proxy) => { }

    // 非必须 报表类型  1.日报  2.月报  3.季报  5.自定义时间的日报   默认按日统计
    const handleItemClick = (item) => {
        state.sale_title.value = item.time + '采购额'

        // 转换时间格式
        const formattedTime = formatTimeString(item.time)
        state.sale_day_timestr.value = formattedTime
        state.sale_day_old_timestr.value = formattedTime
        loadReport2ShopConut(item)
    }

    // 配置月报和季报
    const loadReport2ShopConut = (item) => {
        let param = {
            ...state.reqQuery.value,
            page: state.reqQuery.value.pageTow, //分页参数 
            group: state.reqQuery.value.group == 3 ? "2" : state.reqQuery.value.group == 2 ? "1" : state.reqQuery.value.group,
            stime: item.timestr,
        }
        https.getReportPuchaseConut(param, back);
        function back(data) {
            if (!data) {
                return;
            }
            if (data.status == 1) {

                if (!data.data) {
                    return;
                }
                data = data.data;
                // 总金额
                state.count_2all.value = data?.count_all || {}
                // 列表
                state.count_2ls.value = state.count_2ls.value.concat(data?.count_ls || [])
                state.hasMore2.value = (data?.count_ls && data?.count_ls?.length) >= PAGE_SIZE
            }
        }
    }

    // 点击日
    const itemDayClick = (item) => {
        console.log("itemDayClick=", item)
    }

    // 点击月  专门获取日报表列表
    const isMonthClick = (item) => {
        // 深拷贝参数，避免修改原始数据
        state.sale_2title.value = item.time + '采购额'
        // 转换时间格式
        const formattedTime = formatTimeString(item.time)
        state.sale_day_timestr.value = formattedTime
        state.sale_day_old_timestr.value = formattedTime

        let param = JSON.parse(JSON.stringify(state.reqQuery.value));
        state.loading.value = true
        param.page = 1
        param.group = '1'
        param.pfrom = 0
        param.stime = item.timestr
        // 销售表首页接口  所有都是调用次接口
        https.getReportPuchaseConut(param, back);
        function back(data) {
            state.loading.value = false
            if (!data) {
                return;
            }
            if (data.status == 1) {
                if (!data.data) {
                    return;
                }
                data = data.data;
                // 总金额
                state.count_day_all.value = data?.count_all || {}
                // 列表
                state.count_day_ls.value = state.count_day_ls.value.concat(data?.count_ls || [])
                // state.hasMore.value = (data?.count_ls && data?.count_ls?.length) >= PAGE_SIZE
            }
        }
    }

    // 点击日，看销量情况  shopSellPfrom
    const handleShopSellLsClick = async (item) => {
        state.sale_day_title.value = item.time + '采购额'
        state.sale_day_timestr.value = item.timestr

        let param = {
            time: 1, //分页参数 
            stime: item.timestr,
            storeid: state.reqQuery.value.storeid,
            pfrom: state.shopSellPfrom.value, //非必须 分页参数 - 页面
            pnum: staticConst.PAGE_SIZE, //非必须 分页参数 - 页面显示数量
            is_yy: 1, //预约板块1是2 否 默认否
            uid_cp: state.reqQuery.value.uid_cp, //成员id
        }
        // await https.getReportShopSellList(param, back);
        await https.getReportPuchaseSellList(param, back);
        function back(data) {
            if (!data) return;
            if (data.status == 1) {
                let result = data?.data
                state.shopsell_count_all.value = result?.count || {};
                state.shopsell_count__ls.value = state.shopsell_count__ls.value.concat(result?.data || []);
                state.hasMoreShopSell.value = (result?.data && result.data?.length) >= PAGE_SIZE
            }
        }
    }

    //采购报表 导出数据表格
    const purchaseModuleExportReport = async () => {
        let param = {
            storeid: state.reqQuery.value.storeid,
            stime: state.sale_day_timestr.value,
            time: state.stime_type.value, // 非必须 时间筛选  1日 2月 3季 4年 5 自定义  默认为1 此项可不填
        }
        console.log("param-x-", param)
        let res = await Vue.prototype.$api({ url: config.report_cg_sell_export, data: param });
        if (res.status == 1) {
            if (res.data.ls && res.data.ls.length > 0) {
                downloadExcel(res.data)
            } else {
                Vue.prototype.$message.error('导出失败：没有数据')
            }
        }
    }


    // 仓库------------------------  start ----------------------

    // 仓库列表
    const loadWarehouseList = () => {
        let param = {}
        https.getReportStoreCount(param, back);
        function back(data) {
            state.count_warehouse_ls.value = data?.data || []
            if (state.count_warehouse_ls.value.length > 0) {
                state.warehouse_currentId.value = state.count_warehouse_ls.value[1].store_id
                if (state.warehouse_currentId.value) {
                    loadWarehouseDetail()
                }
            }
        }
    }

    // 仓库详情
    const loadWarehouseDetail = () => {
        if (!state.warehouse_currentId.value) {
            return
        }
        let param = {
            storeid: state.warehouse_currentId.value,
        }
        state.warehouse_class_list_loading.value = true
        https.getReportStoreView(param, back);
        function back(data) {
            if (data.status == 1) {
                state.warehouse_class_info.value = data?.data?.info || {}
                state.warehouse_class_list.value = data?.data?.list || []
            }
            state.warehouse_class_list_loading.value = false
        }
    }

    // 第二个表格商品
    const getStoreViewListData = (data) => {
        state.warehouse_clickItem.value = data
        state.warehouse_showBack.value = true
        state.warehouse_goods_list_loading.value = true
        let param = {
            storeid: state.warehouse_currentId.value,
            catid: state.warehouse_clickItem.value.catid,
            pfrom: state.warehouse_goods_list_pfrom.value,
            pnum: state.warehouse_goods_list_pnum.value,
        }
        https.getReportStoreViewList(param, back);
        function back(data) {
            if (!data) return;
            if (data.status == 1) {
                if (!data.data) return;
                data = data.data;
                if (data.info) {
                    state.warehouse_catTitle.value = data.info;
                }
                if (data.list) {
                    state.warehouse_goods_list.value = state.warehouse_goods_list.value.concat(data.list);
                    state.warehouse_goods_list_pfrom.value++;
                }
            }
            state.warehouse_goods_list_loading.value = false
        }
    }

    // 返回上级
    const goBack = () => {
        state.warehouse_showBack.value = false
        state.warehouse_clickItem.value = {}
    }

    // 点击第二个表格商品
    const clickGoodsItems = () => {
        state.warehouse_goods_info_loading.value = true
        let param = {
            gdid: state.warehouse_gdid.value,
        }
        https.getGoodsStore(param, back);
        function back(data) {
            if (data.status == 1) {
                data = data?.data
                state.warehouse_goods_info.value = data?.info || {}
                state.warehouse_goods_list_ls.value = data?.list || []
            }
            state.warehouse_goods_info_loading.value = false
        }
    }

    // 仓库流水
    const warehouseFlow = () => {
        state.warehouse_flow_list_loading.value = true
        let param = {
            id: state.warehouse_flow_info.value.id,
            ch: "goods",
            pfrom: state.warehouse_flow_list_pfrom.value,
            pnum: staticConst.PAGE_SIZE,
        }
        https.getGoodsStoreLog(param, back);
        function back(data) {
            if (data.status == 1) {
                data = data?.data
                state.warehouse_flow_list.value = state.warehouse_flow_list.value.concat(data.list || [])
                state.warehouse_flow_shop_info.value = data.info || {}
                state.warehouse_flow_list_hasMore.value = (data.list && data.list?.length) >= PAGE_SIZE
            }
            state.warehouse_flow_list_loading.value = false
        }
    }

    const flowLoadMoreData = () => {
        if (state.warehouse_flow_list_loading.value || !state.warehouse_flow_list_hasMore.value) {
            return
        }
        state.warehouse_flow_list_pfrom.value += 20
        warehouseFlow()
    }

    // 仓库流水详情
    const warehouseFlowDetail = () => {
        let param = {
            log_id: state.warehouse_flow_row_info.value.log_id,
            ch: "goods",
        }
        https.getGoodsStoreLogDetail(param, back);
        function back(data) {
            console.log("data--", data)
            if (data.status == 1) {
                data = data?.data
                state.warehouse_flow_detail.value = data || {}
            }
        }
    }

    //仓库报表导出数据表格
    const exportReport = async () => {
        let param = {
            storeid: state.warehouse_currentId.value,
            catid: state.warehouse_clickItem.value.catid,
        }
        let res = await Vue.prototype.$api({ url: config.report_store_gd_export, data: param });
        if (res.status == 1) {
            if (res.data.ls && res.data.ls.length > 0) {
                downloadExcel(res.data)
            } else {
                Vue.prototype.$message.error('导出失败：没有数据')
            }
        }
    }
    // 仓库------------------------  end ----------------------


    // 自定义表头映射
    const downloadExcel = async (data) => {

        // 根据 title 表头循环，从 list 数组对象中取值，生成新的 list
        let newList = data.ls.map(item => {
            let newItem = {}
            // 循环 title 对象的每个键
            for (let key in data.title) {
                // 如果 list 中的 item 包含这个字段，则提取其值
                if (item.hasOwnProperty(key)) {
                    newItem[key] = item[key]
                } else {
                    // 如果没有这个字段，设置为空字符串或默认值
                    newItem[key] = ''
                }
            }
            return newItem
        })
        try {
            const success = await ExcelExporter.export(
                newList, // 数据
                `${data.sheet_title}.xlsx`,
                data.title // 表头
            )
            if (success) {
                Vue.prototype.$message.success('成功导出表格,请保存')
            }
        } catch (error) {
            Vue.$message.error('导出失败：' + error?.message)
        }
    }

    const warehouseLoadMoreData = () => {
        console.log("warehouseLoadMoreData")
    }

    return {
        ...state,
        loadReportShopConut,
        loadMoreData,
        selectHandleChange,
        selectDate,
        resetState,
        exportData,
        handleItemClick,
        reset2State,
        itemDayClick,
        isMonthClick,
        handleShopSellLsClick,
        purchaseModuleExportReport,

        // 仓库
        loadWarehouseList,
        warehouseLoadMoreData,
        loadWarehouseDetail,
        getStoreViewListData,
        goBack,

        // 点击商品
        clickGoodsItems,

        // 仓库流水
        warehouseFlow,
        warehouseFlowDetail,
        flowLoadMoreData,

        // 导出
        exportReport
    }
} 